package boot.spring.config;

import boot.spring.bean.SessionBean;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class AbstractWebSocketHandlerConfig extends AbstractWebSocketHandler {
    private static Map<String, SessionBean> sessionBeanMap;
    private static  AtomicInteger clientIdMaker;
    static {
        sessionBeanMap = new ConcurrentHashMap<>();
        clientIdMaker = new AtomicInteger(0);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        SessionBean sessionBean = new SessionBean(session, clientIdMaker.getAndIncrement());
        sessionBeanMap.put(session.getId(), sessionBean);
        log.info("客户端上线: "+ sessionBean.getClientId() +";clientId = "+sessionBean.getWebSocketSession().getId());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
       super.handleMessage(session, message);
    }

    /**
     * 收到消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        SessionBean sessionBean = sessionBeanMap.get(session.getId());
        log.info(session.getId()+" 发送消息: "+ message.getPayload());
    }

    /**
     * 传输异常的时候，怎么操作
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 如果开启着 ，则关闭，并从map中删除掉
        log.info(session.getId()+" handleTransportError 执行之前 : " + exception.getMessage());
        super.handleTransportError(session, exception);
        log.info(session.getId()+" handleTransportError 执行之后 : " + exception.getMessage());
        if (session.isOpen()){
            session.close();
        }
        sessionBeanMap.remove(session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        SessionBean sessionBean = sessionBeanMap.get(session.getId());
        log.info(sessionBean.getClientId()+" 连接关闭了！");
    }
}
